package com.kinglone.back.music.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.kinglone.back.music.model.Music;
import com.kinglone.back.music.service.MusicService;
import com.kinglone.common.entity.PageBean;
import com.kinglone.common.utils.DateUtils;
import com.kinglone.common.utils.PropertieUtil;
import com.kinglone.common.utils.ResponseUtil;

@Controller
@RequestMapping("/back/music")
public class MusicController {

	@Autowired
	private MusicService musicService;
	
	/**
	 * 分页查询音乐列表
	 * @param page
	 * @param rows
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public String list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,
			HttpServletResponse response)throws Exception{
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Music> musicList = musicService.list(map);
		Long total = musicService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(musicList);	
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 添加音乐
	 * @param musicFile
	 * @param music
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(@RequestParam("musicFile") MultipartFile musicFile,Music music,HttpServletResponse response)throws Exception{
		JSONObject result = new JSONObject();
		int resultTotal=0;
		System.out.println("----------:"+music.getIfUse());
		if(music.getId() == null){
			if(!musicFile.isEmpty()){
				//上传文件名
	           String filename = musicFile.getOriginalFilename();
	           String fileType = filename.substring(filename.lastIndexOf(".")+1);   //文件格式 
	           if(!"mp3".equals(fileType)){
	        	   result.put("success", false);
	        	   result.put("message", "请选择音乐!");
	        	   ResponseUtil.write(response, result);
	        	   return null;
	           }           
				long length = musicFile.getSize();
				System.out.println("文件大小："+length);
				//上传路径
				String basepath = PropertieUtil.getValue("config.properties", "upload_url");
				//相对保存路径
				String relativePath="/upload/music/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
				String holePath=basepath+relativePath;
				System.out.println("完整存储路径："+holePath);
				File f=new File(holePath);
				if(!f.exists()){
					f.mkdirs();
				}		
	       		//组成文件实际路径 
	        	String truePath=holePath+filename;
	        	System.out.println("实际路径为："+truePath);       	
	        	musicFile.transferTo(new File(truePath));
	        	String musicUrl = relativePath+filename;
	        	music.setMusicUrl(musicUrl);
	        	resultTotal = musicService.save(music);
			}
		}else{
			resultTotal = musicService.update(music);
		}		
		if(resultTotal > 0){
			 result.put("success", true);
		}else{
			result.put("success", false);
			result.put("message", "上传失败!");
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 删除音乐
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		String[] arrIds = ids.split(",");
		for(int i=0;i<arrIds.length;i++){
			String musicUrl = musicService.getMusicById(Integer.parseInt(arrIds[i]));
			String basepath=PropertieUtil.getValue("config.properties", "upload_url");
			File deleteFile = new File(basepath+musicUrl);   //删除原文件
      	  	deleteFile.delete();
			musicService.delete(Integer.parseInt(arrIds[i]));
		}
		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
}
